<?php


namespace App\Api\Controllers\AlipayOpen;

use Alipayopen2019\request\AlipayMarketingVoucherQueryRequest;
use App\Api\Controllers\Config\AlipayIsvConfigController;
use Illuminate\Http\Request;
use Alipayopen2019\AopClient as AopClient2019;
use Alipayopen2019\Request\AlipayMarketingCashlessvoucherTemplateCreateRequest;
use Alipayopen2019\Request\AlipayMarketingCashlessvoucherTemplateModifyRequest;
use Alipayopen2019\Request\AlipayMarketingVoucherSendRequest;
use Alipayopen2019\Request\AlipayMarketingExchangevoucherUseRequest;
use Alipayopen2019\request\AlipayMarketingVoucherTemplatedetailQueryRequest;
use App\Models\AlipayCashCoupons;
use App\Models\AlipayCashCards;
use App\Models\Store;
use App\Models\AlipayCashlessVoucher;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class CashCouponController extends \App\Api\Controllers\BaseController
{


    //无资金券模板创建接口
    public function createCoupon(Request $request)
    {
        try {

            $user_token = $this->parseToken();
            $config_id = $request->get('config_id', $user_token->config_id);
            $user_id = $request->get('user_id', $user_token->user_id);
            $store_id = $request->get('store_id', $user_token->user_id);
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店不存在或状态异常,请联系管理员'
                ]);
            }
            $auth = DB::table('alipay_app_oauth_users')->where('store_id', $store_id)->first();
            if(!$auth) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店未进行授权请去授权操作'
                ]);
            }
            if(!$auth->alipay_user_id){
                return json_encode([
                    'status' => 2,
                    'message' => '门店未绑定正确的支付宝门店id'
                ]);
            }
            if(!$auth->app_auth_token){
                return json_encode([
                    'status' => 2,
                    'message' => '门店未绑定正确的授权码'
                ]);
            }
            //券类型
            $voucher_type = $request->get('voucher_type', 'CASHLESS_FIX_VOUCHER');
            //品牌名
            $brand_name = $request->get('brand_name', '');
            //发放开始时间
            $publish_start_time = $request->get('publish_start_time', '');
            $publish_start_time_s =strtotime($publish_start_time);
            //发放开结束时间
            $publish_end_time = $request->get('publish_end_time', '');
            $publish_end_time_e =strtotime($publish_end_time);
            //当前时间
            $now_time = time();
            $start_time = strtotime($publish_start_time);
            //券生效时间
            $start = $request->get('start', '');
            //失效时间
            $end = $request->get('end', '');
            //券可用时段
            $day_rule = $request->get('day_rule', '');
            $time_begin = $request->get('time_begin', '');
            $time_end = $request->get('time_end', '');
            //券使用说明
            $description = $request->get('description', '');
            //拟发行券的数量
            $voucher_quantity = $request->get('quantity', '');
            //面额
            $amount = $request->get('amount', '');
            //最低额度
            $floor_amount = $request->get('floor_amount', '');
            $check_data = [
                'voucher_type' => '券类型',
                'brand_name' => '品牌名',
                'publish_start_time' => '发放开始时间',
                'publish_end_time' => '发放开结束时间',
                'start' => '券生效时间',
                'end' => '失效时间',
                'day_rule' => '券可用时段星期',
                'time_begin' => '券可用时段',
                'time_end' => '券可用时段',
                'description' => '券使用说明',
                'quantity' => '拟发行券的数量',
                'amount' => '面额',
                'floor_amount' => '最低额度',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }
            if(!($start_time-$now_time>=0) || !($start_time-$now_time<=1296000)){
                return json_encode([
                    'status' => 2,
                    'message' => '发放开始时间不能大于当前时间15天'
                ]);
            }
            if(!($publish_end_time_e-$publish_start_time_s>=0) || !($publish_end_time_e-$publish_start_time_s<=7776000)){
                return json_encode([
                    'status' => 2,
                    'message' => '券的发放结束时间和发放开始时间跨度不能大于90天'
                ]);
            }
            //券有效期
            $voucher_valid_period = array(
                'type' => 'ABSOLUTE',
                'start' => $start,
                'end' => $end,
            );
            //券可用时段
            $voucher_available_time = array(
                array(
                    'day_rule' => $day_rule,
                    'time_begin' => $time_begin,
                    'time_end' => $time_end,
                )
            );
            //外部业务单号
            $out_biz_no = date("YmdHis").time();
            if(!$description){
                $voucher_description = [];
            }else{
                $voucher_description = array(
                    0 => $description,
                );
            }
            $rule_conf = array(
                'PID' => $auth->alipay_user_id,
            );
            $config_type = '01';
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
            $aop = new AopClient2019();
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='utf-8';
            $aop->charset='utf-8';
            $aop->timestamp= date("Y-m-d H:i:s",time());
            $aop->format='json';
            $aop->method = 'alipay.marketing.cashlessvoucher.template.create';
            $app_auth_token = $auth->app_auth_token;
            $requests = new AlipayMarketingCashlessvoucherTemplateCreateRequest();
            $data_re_arr = array(
                'voucher_type' => $voucher_type,
                'brand_name' => $brand_name,
                'publish_start_time' => $publish_start_time,
                'publish_end_time' => $publish_end_time,
                'voucher_valid_period' => $voucher_valid_period,
                'voucher_available_time' => $voucher_available_time,
                'out_biz_no' => $out_biz_no,
                'voucher_description' => $voucher_description,
                'voucher_quantity' => $voucher_quantity,
                'amount' => $amount,
                'floor_amount' => $floor_amount,
                'rule_conf' => $rule_conf,

            );
            $data_re = json_encode($data_re_arr);
            $requests->setBizContent($data_re);
            $result = $aop->execute($requests, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            $voucher_available = json_encode($voucher_available_time);
            if(isset($description)){
                $voucher_description = json_encode($description);
            }
            //异常
            if ($resultCode == 40004) {
                return json_encode([
                    'status' => 2,
                    'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                    'result_code' => $resultCode,
                ]);
            } else {
                if (!empty($resultCode) && $resultCode == 10000) {
                    $operationInfo = AlipayCashCoupons::where('template_id', $result->$responseNode->template_id)->first();
                    if(!$operationInfo){
                        $data = [
                            'config_id' => $config_id,
                            'store_id' => $store_id,
                            'template_id' => $result->$responseNode->template_id,
                            'voucher_type' => 1,
                            'brand_name' => $brand_name,
                            'publish_start_time' => $publish_start_time,
                            'publish_end_time' => $publish_end_time,
                            'voucher_start' => $start,
                            'voucher_end' => $end,
                            'voucher_available_time'=> $voucher_available,
                            'out_biz_no'=> $out_biz_no,
                            'voucher_description'=> isset($voucher_description) ? $voucher_description : "",
                            'amount' => $amount,
                            'voucher_quantity' => $voucher_quantity,
                            'floor_amount' => $floor_amount,
                        ];
                        $obj = AlipayCashCoupons::create($data);
                        if (!$obj) {
                            return json_encode([
                                'status' => 2,
                                'message' => '创建失败'
                            ]);
                        }
                    }
                    return json_encode([
                        'status' => 1,
                        'message' => '创建成功',
                        'data' => $data_re_arr,
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                        'result_code' => $resultCode,
                    ]);
                }

            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    //无资金营销活动
    public function createCashlessCoupon(Request $request)
    {
        try {
            $user_token = $this->parseToken();
            $config_id = $request->get('config_id', $user_token->config_id);
            $user_id = $request->get('user_id', $user_token->user_id);
            $store_id = $request->get('store_id', $user_token->user_id);
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店不存在或状态异常,请联系管理员'
                ]);
            }
            //活动名称
            $activity_name = $request->get('activity_name', '');
            //券类型
            $voucher_type = $request->get('voucher_type', 'CASHLESS_FIX_VOUCHER');
            //品牌名
            $brand_name = $request->get('brand_name', '');
            //发放开始时间
            $publish_start_time = $request->get('publish_start_time', '');
            $publish_start_time_s =strtotime($publish_start_time);
            //发放开结束时间
            $publish_end_time = $request->get('publish_end_time', '');
            $publish_end_time_e =strtotime($publish_end_time);
            //当前时间
            $now_time = time();
            $start_time = strtotime($publish_start_time);
            //券生效时间
            $start = $request->get('start', '');
            //失效时间
            $end = $request->get('end', '');
            //券可用时段
            $day_rule = $request->get('day_rule', '');
            $time_begin = $request->get('time_begin', '');
            $time_end = $request->get('time_end', '');
            //券使用说明
            $description = $request->get('description', '');
            //拟发行券的数量
            $voucher_quantity = $request->get('quantity', '');
            //面额
            $amount = $request->get('amount', '');
            //最低额度
            $floor_amount = $request->get('floor_amount', '');
            $check_data = [
                'activity_name' => '券名称',
                'voucher_type' => '券类型',
                'brand_name' => '品牌名',
                'publish_start_time' => '发放开始时间',
                'publish_end_time' => '发放开结束时间',
                'start' => '券生效时间',
                'end' => '失效时间',
                'day_rule' => '券可用时段星期',
                'time_begin' => '券可用时段',
                'time_end' => '券可用时段',
                'description' => '券使用说明',
                'quantity' => '拟发行券的数量',
                'amount' => '面额',
                'floor_amount' => '最低额度',
            ];
            $check = $this->check_required($request->except(['token']), $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }
            if(!($start_time-$now_time>=0) || !($start_time-$now_time<=1296000)){
                return json_encode([
                    'status' => 2,
                    'message' => '发放开始时间不能大于当前时间15天'
                ]);
            }
            if(!($publish_end_time_e-$publish_start_time_s>=0) || !($publish_end_time_e-$publish_start_time_s<=7776000)){
                return json_encode([
                    'status' => 2,
                    'message' => '券的发放结束时间和发放开始时间跨度不能大于90天'
                ]);
            }

            $data = [
                'config_id' => $config_id,
                'store_id' => $store_id,
                'activity_name' => $activity_name,
                'voucher_type' => 1,
                'brand_name' => $brand_name,
                'publish_start_time' => $publish_start_time,
                'publish_end_time' => $publish_end_time,
                'voucher_start' => $start,
                'voucher_end' => $end,
                'voucher_time_start'=> $time_begin,
                'voucher_time_end'=> $time_end,
                'day_rule' => $day_rule,
                'voucher_description'=> isset($description) ? $description : "",
                'amount' => $amount,
                'voucher_quantity' => $voucher_quantity,
                'floor_amount' => $floor_amount,
            ];
            $obj = AlipayCashlessVoucher::create($data);
            if ($obj) {
                return json_encode([
                    'status' => 1,
                    'message' => '创建成功'
                ]);
            } else {
                return json_encode([
                    'status' => 1,
                    'message' => '创建失败',
                ]);
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    //无资金商户列表
    public function CashlessList(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $storeId = $request->get('storeId', '');
//            dd($storeId);
            $where = [];
            if ($storeId) {
                $where[] = ['store_id', '=', $storeId];
            }
            $where[] =  ['del_status', '=', 1];
            $obj = DB::table('alipay_cashless_voucher')->where($where)
                ->orderBy('created_at', 'desc');
            $this->message = '数据返回成功';
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('updated_at', 'desc')->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }

    //无资金服務商列表
    public function CashlessUserList(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $where = [];
            if ($config_id) {
                $where[] = ['config_id', '=', $config_id];
            }
            $where[] =  ['del_status', '=', 1];
            $obj = DB::table('alipay_cashless_voucher')->where($where)
                ->orderBy('created_at', 'desc');
            $this->message = '数据返回成功';
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('updated_at', 'desc')->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }

    //优惠券单条信息
    public function CashlessInfo(Request $request)
    {
        try {
            $public = $this->parseToken();

            $id = $request->get('id', '');
            $Cashless = AlipayCashlessVoucher::where('id', $id)->first();

            $store_id = $Cashless->store_id;


            $Store = Store::where('store_id', $store_id)
                ->select('store_name')
                ->get();

            $store_names = '';
            if (!$Store->isEmpty()) {
                foreach ($Store as $k => $v) {
                    $store_names = $store_names . $v->store_name ;
                }
            }

            $Cashless->store_names = $store_names;
            log::info($Cashless);

            $this->message = '数据返回成功';
            return $this->format($Cashless);

        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    //服务商审核
    public function checkStatus(Request $request)
    {

        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id', '');
            $status = $request->get('status', '1');
            $id = $request->get('id', '');
            $Store = Store::where('store_id', $store_id)->first();
            if (!$Store) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店不存在'
                ]);
            }
            $obj = AlipayCashlessVoucher::where('id', $id)
                ->update(['status' => $status]);
            if ($obj) {
                return json_encode([
                    'status' => 1,
                    'message' => '卡券审核通过',
                    'data' => $request->except(['token'])
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '卡券审核不通过',
                    'data' => $request->except(['token'])
                ]);
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }

    }

    //商户删除(假删除)
    public function CashlessDel(Request $request)
    {

        try {
            $user = $this->parseToken();
            $id = $request->get('id', '');
            $obj = AlipayCashlessVoucher::where('id', $id)
                ->update(['del_status' => 2]);
            if ($obj) {
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功',
                    'data' => $request->except(['token'])
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '删除失败',
                    'data' => $request->except(['token'])
                ]);
            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage() . $exception->getFile()
            ]);
        }

    }

    //服务商删除(真删)
    public function CashlessUserDel(Request $request)
    {
        try {
            $public = $this->parseToken();
            $id = $request->get('id', '');
            $obj = AlipayCashlessVoucher::where('id', $id)->delete();
            if ($obj) {
                return json_encode([
                    'status' => 1,
                    'message' => '删除成功',
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => '删除失败',
                ]);
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }

    public function couponList(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $storeId = $request->get('storeId', '');
//            dd($storeId);
            $where = [];
            if ($storeId) {
                $where[] = ['store_id', '=', $storeId];
            }
            $obj = DB::table('alipay_cash_coupons')->where($where)
                ->orderBy('created_at', 'desc');
            $this->message = '数据返回成功';
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('updated_at', 'desc')->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);

        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }

    //无资金券模板修改接口
    public function couponUp(Request $request)
    {
        try {

            $user_token = $this->parseToken();
            $config_id = $request->get('config_id', $user_token->config_id);
            $user_id= $request->get('user_id', $user_token->user_id);
            //券类型
            $id = $request->get('id', '');
            $publish_end_time = $request->get('publish_end_time', '');
            $coupons = AlipayCashCoupons::where('id', $id)->first();
            if (!$coupons) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有此模板'
                ]);

            }
            $store_id = $request->get('store_id', $user_token->user_id);
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店不存在或状态异常,请联系管理员'
                ]);
            }
            $auth = DB::table('alipay_app_oauth_users')->where('store_id', $store_id)->first();
            if(!$auth) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店未进行授权请去授权操作'
                ]);
            }
            if(!$auth->app_auth_token){
                return json_encode([
                    'status' => 2,
                    'message' => '门店未绑定正确的授权码'
                ]);
            }
            $publish_start_time = $coupons->publish_start_time;
            $publish_start_time_s =strtotime($publish_start_time);
            //发放开结束时间
            $publish_end_time_e =strtotime($publish_end_time);
            $template_id = $coupons->template_id;
            $out_biz_no = $coupons->out_biz_no;
            $end_time = $coupons->publish_end_time;
            $end_time =strtotime($end_time);
            if(!($publish_end_time_e-$end_time>=0) ){
                return json_encode([
                    'status' => 2,
                    'message' => '仅支持延长发券时间'
                ]);
            }

            if(!($publish_end_time_e-$publish_start_time_s>=0) || !($publish_end_time_e-$publish_start_time_s<=7776000)){
                return json_encode([
                    'status' => 2,
                    'message' => '券的发放结束时间和发放开始时间跨度不能大于90天'
                ]);
            }

            $config_type = '01';
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
            $aop = new AopClient2019();
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='utf-8';
            $aop->charset='utf-8';
            $aop->timestamp= date("Y-m-d H:i:s",time());
            $aop->format='json';
            $aop->method = 'alipay.marketing.cashlessvoucher.template.modify';
            $app_auth_token = $auth->app_auth_token;
            $requests = new AlipayMarketingCashlessvoucherTemplateModifyRequest();
            $data_re_arr = array(
                'template_id' => $template_id,
                'publish_end_time' => $publish_end_time,
                'out_biz_no' => $out_biz_no,
            );
            $data_re = json_encode($data_re_arr);
            $requests->setBizContent($data_re);
            $result = $aop->execute($requests, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if(isset($result->$responseNode->template_id)){
                $resultBatchNo = $result->$responseNode->template_id;
            }
            //异常
            if ($resultCode == 40004) {
                return json_encode([
                    'status' => 2,
                    'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                    'result_code' => $resultCode,
                ]);
            } else {
                if (!empty($resultCode) && $resultCode == 10000) {
                        $data = [
                            'publish_end_time' => $publish_end_time,
                        ];
                        $obj = AlipayCashCoupons::where('id', $id)->update($data);
                        if (!$obj) {
                            return json_encode([
                                'status' => 2,
                                'message' => '修改失败'
                            ]);
                        }
                    return json_encode([
                        'status' => 1,
                        'message' => '修改成功',
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                        'result_code' => $resultCode,
                    ]);
                }

            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }

    //无资金券发券接口
    public function sendCoupon($open_id,$state)
    {
        try {
            $config_id = $state['config_id'];
            $open_id = $open_id;
            $store_id = $state['store_id'];
            $template_id = $state['template_id'];
            $where = [];
            if ($store_id) {
                $where[] = ['store_id', '=', $store_id];
            }
            if ($template_id) {
                $where[] = ['template_id', '=', $template_id];
            }

            //券类型
            $coupons = AlipayCashCoupons::where($where)->first();
            if (!$coupons) {
                return json_encode([
                    'status' => 2,
                    'message' => '商户没有券'
                ]);
            }

            $auth = DB::table('alipay_app_oauth_users')->where('store_id', $store_id)->first();
            if(!$auth->app_auth_token){
                return json_encode([
                    'status' => 2,
                    'message' => '门店未绑定正确的授权码'
                ]);
            }

            //外部业务单号
            $config_type = '01';
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
            $aop = new AopClient2019();
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='utf-8';
            $aop->charset='utf-8';
            $aop->timestamp= date("Y-m-d H:i:s",time());
            $aop->format='json';
            $aop->method = 'alipay.marketing.voucher.send';
            $requests = new AlipayMarketingVoucherSendRequest();
            $app_auth_token = $auth->app_auth_token;
            $data_re_arr = array(
                'template_id' => $coupons->template_id,
                'user_id' => $open_id,
                'out_biz_no' => $coupons->out_biz_no,
            );
            $data_re = json_encode($data_re_arr);
            $requests->setBizContent($data_re);
            $result = $aop->execute($requests, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;

            //异常
            if ($resultCode == 40004) {
                return json_encode([
                    'status' => 2,
                    'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                ]);
            } else {
                if (!empty($resultCode) && $resultCode == 10000) {
                    $whereCash = [];
                    $whereCash[] = ['alipay_user_id', '=', $result->$responseNode->user_id];
                    $whereCash[] = ['template_id', '=', $template_id];
                    $cashCoupons = AlipayCashCards::where($whereCash)->first();
                    if(!$cashCoupons){
                        $data = [
                            'config_id' => $config_id,
                            'brand_name' => $coupons->brand_name,
                            'store_id' => $store_id,
                            'template_id' => $template_id,
                            'voucher_id' => $result->$responseNode->voucher_id,
                            'alipay_user_id' => $result->$responseNode->user_id,
                            'out_biz_no' => $coupons->out_biz_no,
                            'status' => 1,
                        ];
                        $obj = AlipayCashCards::create($data);
                        if (!$obj) {
                            return json_encode([
                                'status' => 2,
                                'message' => '创建失败'
                            ]);
                        }
                    }else{
                        return json_encode([
                            'status' => 2,
                            'message' => '该券用户只能领取一张'
                        ]);

                    }
                    return json_encode([
                        'status' => 1,
                        'message' => '发券成功',
                        'voucher_id' => $result->$responseNode->voucher_id,
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                        'result_code' => $resultCode,
                    ]);
                }

            }
        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }


    //无资金券使用接口
    public function useCoupon(Request $request)
    {
        try {
//            return json_encode(['status' => 1, 'message' => '操作成功', 'data' => $request->except(['token'])]);

            $user_token = $this->parseToken();
            $config_id = $request->get('config_id', $user_token->config_id);
            $user_id= $request->get('user_id', $user_token->user_id);
//            $alipay_user_id = $request->get('alipay_user_id', '');
            $store_id = $request->get('store_id', '12345');

            //券类型
            $coupons = AlipayCashCoupons::where('store_id', $store_id)->first();
            if (!$coupons) {
                return json_encode([
                    'status' => 2,
                    'message' => '没有此模板'
                ]);
            }

            //外部业务单号
            $out_biz_no = date("YmdHis").time();
            $config_type = '01';
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
            $aop = new AopClient2019();
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='utf-8';
            $aop->charset='utf-8';
            $aop->timestamp= date("Y-m-d H:i:s",time());
            $aop->format='json';
            $aop->method = 'alipay.marketing.exchangevoucher.use';
            $app_auth_token = '202101BB92055fce76e9429eb1af251b90054X31';
            $requests = new AlipayMarketingExchangevoucherUseRequest();
            $data_re_arr = array(
                'voucher_id' => '20210201000730026591073NZZH2',
                'user_id' => '2088332067491654',
                'out_biz_no' => '202102011029041612146544',
            );
            $data_re = json_encode($data_re_arr);
            $requests->setBizContent($data_re);
            $result = $aop->execute($requests, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            dd($result->$responseNode);
            if(isset($result->$responseNode->template_id)){
                $resultBatchNo = $result->$responseNode->template_id;
            }
            //异常
            if ($resultCode == 40004) {
                return json_encode([
                    'status' => 2,
                    'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                ]);
            } else {
                if (!empty($resultCode) && $resultCode == 10000) {

                    $data = [
                        'voucher_id' => $result->$responseNode->voucher_id,
                        'alipay_user_id' => $result->$responseNode->user_id,
                        'user_id'  => $user_id,
                    ];
                    $obj = AlipayCashCards::where('id', $id)->update($data);
                    if (!$obj) {
                        return json_encode([
                            'status' => 2,
                            'message' => '修改失败'
                        ]);
                    }
                    return json_encode([
                        'status' => 1,
                        'message' => '修改成功',
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                        'result_code' => $resultCode,
                    ]);
                }

            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }
    }


    //券模板详情
    public function couponDetailQuery(Request $request)
    {
        try {
            $store_id = $request->get('storeId', ''); //系统门店id
            $template_id = $request->get('templateId', ''); //券模板ID

            if (!isset($store_id) && empty($store_id)) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店id,为必传参数'
                ]);
            }

            if (!isset($template_id) && empty($template_id)) {
                return json_encode([
                    'status' => 2,
                    'message' => '券模板ID,为必传参数'
                ]);
            }


            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店不存在或状态异常,请联系管理员'
                ]);
            }
            $auth = DB::table('alipay_app_oauth_users')->where('store_id', $store_id)->first();
            if(!$auth) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店未进行授权请去授权操作'
                ]);
            }
            if(!$auth->app_auth_token){
                return json_encode([
                    'status' => 2,
                    'message' => '门店未绑定正确的授权码'
                ]);
            }

            $config_id = $storeObj->config_id;

            $config_type = '01';
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
            $aop = new AopClient2019();
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='utf-8';
            $aop->charset='utf-8';
            $aop->timestamp= date("Y-m-d H:i:s",time());
            $aop->format='json';
            $aop->method = 'alipay.marketing.voucher.templatedetail.query';
            $app_auth_token = $auth->app_auth_token;
            $requests = new AlipayMarketingVoucherTemplatedetailQueryRequest();
            $data_re_arr = array(
                'template_id' =>  $template_id,
            );
            $data_re = json_encode($data_re_arr);
            $requests->setBizContent($data_re);
            $result = $aop->execute($requests, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            //异常
            if ($resultCode == 40004) {
                return json_encode([
                    'status' => 2,
                    'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                    'result_code' => $resultCode,
                ]);
            } else {
                if (!empty($resultCode) && $resultCode == 10000) {
                    return json_encode([
                        'status' => 1,
                        'message' => '查询成功',
                        'data' =>  [
                            'template_id' => $result->$responseNode->template_id, //券模板ID
                            'voucher_type' => $result->$responseNode->voucher_type, //券类型。可枚举，暂时只支持代金券(FIX_VOUCHER)、无资金单品代金券（ITEM_CASHLESS_FIX_VOUCHER）、无资金单品折扣券（ITEM_CASHLESS_DISCOUNT_VOUCHER）、无资金单品特价券（ITEM_CASHLESS_SPE_VOUCHER）
                            'voucher_name' => $result->$responseNode->voucher_name, //券名称
                            'publish_start_time' => $result->$responseNode->publish_start_time, //发放开始时间，格式为：2017-01-01 00:00:01
                            'publish_end_time' => $result->$responseNode->publish_end_time, //发放结束时间，格式为：2017-01-29 23:59:59
                            'status' => $result->$responseNode->status, //模板状态，可枚举。分别为‘草稿’(I)、‘生效’(S)、‘删除’(D)和‘过期’(E)
                            'voucher_valid_period' => $result->$responseNode->voucher_valid_period, //json,券有效期。有两种类型：绝对时间和相对时间。绝对时间有3个key：type、start、end，type取值固定为"ABSOLUTE"，start和end分别表示券生效时间和失效时间，格式为yyyy-MM-dd HH:mm:ss。绝对时间示例：{"type": "ABSOLUTE", "start": "2017-01-10 00:00:00", "end": "2017-01-13 23:59:59"}。相对时间有3个key：type、duration、unit，type取值固定为"RELATIVE"，duration表示从发券时间开始到往后推duration个单位时间为止作为券的使用有效期，unit表示有效时间单位，有效时间单位可枚举：MINUTE, HOUR, DAY。示例：{"type": "RELATIVE", "duration": 1 , "unit": "DAY" }，如果此刻发券，那么该券从现在开始生效1(duration)天(unit)后失效
                            'floor_amount' => $result->$responseNode->floor_amount, //最低额度。券的最低使用门槛金额，只有订单金额大于等于最低额度时券才能使用。币种为人民币，单位为元。该数值不小于0，小数点以后最多保留两位。
                            'voucher_description' => $result->$responseNode->voucher_description, //券使用说明
                            'amount' => $result->$responseNode->amount, //面额。每张代金券可以抵扣的金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位。当券类型为无资金单品券（ITEM_CASHLESS_FIX_VOUCHER、ITEM_CASHLESS_DISCOUNT_VOUCHER、ITEM_CASHLESS_SPE_VOUCHER）时，暂不支持查询本参数，出参为0
                            'voucher_quantity' => $result->$responseNode->voucher_quantity, //拟发行券的数量。单位为张。该数值是大于0的整数
                            'total_amount' => $result->$responseNode->total_amount, //总金额面额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位。仅代金券有效。当券类型为无资金单品券（ITEM_CASHLESS_FIX_VOUCHER、ITEM_CASHLESS_DISCOUNT_VOUCHER、ITEM_CASHLESS_SPE_VOUCHER）时，暂不支持查询本参数，出参为0
                            'publish_count' => $result->$responseNode->publish_count, //已发放张数。单位为张。该数值是大于0的整数
                            'publish_amount' => $result->$responseNode->publish_amount, //已发放总金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
                            'used_count' => $result->$responseNode->used_count, //已使用张数。单位为张。该数值是大于0的整数
                            'used_amount' => $result->$responseNode->used_amount, //已使用总金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
                            'recycle_amount' => isset($result->$responseNode->recycle_amount) ? $result->$responseNode->recycle_amount : 0 //选填,退回金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
                        ]
                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                        'result_code' => $resultCode,
                    ]);
                }

            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }


    }

    //券查询
    public function voucherQuery(Request $request)
    {
        try {
            $store_id = $request->get('storeId', ''); //系统门店id
            $voucher_id = $request->get('voucher_id', ''); //系统门店id
            if (!isset($store_id) && empty($store_id)) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店id,为必传参数'
                ]);
            }
            $storeObj = Store::where('store_id', $store_id)
                ->where('is_close', 0)
                ->where('is_delete', 0)
                ->first();
            if (!$storeObj) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店不存在或状态异常,请联系管理员'
                ]);
            }
            $config_id = $storeObj->config_id;

            $auth = DB::table('alipay_app_oauth_users')->where('store_id', $store_id)->first();
            if(!$auth) {
                return json_encode([
                    'status' => 2,
                    'message' => '门店未进行授权请去授权操作'
                ]);
            }
            if(!$auth->app_auth_token){
                return json_encode([
                    'status' => 2,
                    'message' => '门店未绑定正确的授权码'
                ]);
            }

            $config_type = '01';
            //配置
            $isvconfig = new AlipayIsvConfigController();
            $config = $isvconfig->AlipayIsvConfig($config_id, $config_type);
            $aop = new AopClient2019();
            $aop->gatewayUrl = $config->alipay_gateway;
            $aop->appId = $config->app_id;
            $aop->rsaPrivateKey = $config->rsa_private_key;
            $aop->alipayrsaPublicKey = $config->alipay_rsa_public_key;
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='utf-8';
            $aop->charset='utf-8';
            $aop->timestamp= date("Y-m-d H:i:s",time());
            $aop->format='json';
            $aop->method = 'alipay.marketing.voucher.query';
            $app_auth_token = $auth->app_auth_token;
            $requests = new AlipayMarketingVoucherQueryRequest();
            $data_re_arr = array(
                'voucher_id' => $voucher_id,
            );
            $data_re = json_encode($data_re_arr);
            $requests->setBizContent($data_re);
            $result = $aop->execute($requests, null, $app_auth_token);
            $responseNode = str_replace(".", "_", $requests->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            // 'user_time' => isset($result->$responseNode->bill_details[0]->gmt_create) ? $result->$responseNode->bill_details[0]->gmt_create:'';
            //(ENABLED:可用,DISABLED:不可用,DELETE:删除状态,TRANS:发放中,TRANSFER:已转增,UNC:未领取,USED:已使用,USING:使用中,REFUNDED:已退款,REFUNDING:退款中,UNACTIVE:未激活,EXPIRED:已过期)
            if(isset($result->$responseNode->status)){
                $resultStatus = $result->$responseNode->status;
                if($resultStatus =='ENABLED'){
                    $status = 2;
                }elseif($resultStatus =='DISABLED'){
                    $status = 3;
                }elseif($resultStatus =='USED'){
                    $status = 4;
                }elseif($resultStatus =='EXPIRED'){
                    $status = 5;
                }elseif($resultStatus =='UNACTIVE'){
                    $status = 6;
                }else{
                    $status = 7; //未知状态
                }
            }


            //异常
            if ($resultCode == 40004) {
                return json_encode([
                    'status' => 2,
                    'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                    'result_code' => $resultCode,
                ]);
            } else {
                if (!empty($resultCode) && $resultCode == 10000) {
                    if(isset($result->$responseNode->bill_details[0]->gmt_create)){
                        $data = [
                            'status' => $status,
                            'use_time' => $result->$responseNode->bill_details[0]->gmt_create,
                        ];

                    }else{
                        $data = [
                            'status' => $status,
                        ];

                    }

                    $obj =AlipayCashCards::where('voucher_id', $voucher_id)->update($data);
                    if (!$obj) {
                        return json_encode([
                            'status' => 2,
                            'message' => '更新失败'
                        ]);
                    }
                    return json_encode([
                        'status' => 1,
                        'message' => '更新成功',
                    ]);

//                    return json_encode([
//                        'status' => 1,
//                        'message' => '绑定成功',
//                        'data' =>  [
//                            'template_id' => $result->$responseNode->template_id, //券模板ID
//                            'voucher_type' => $result->$responseNode->voucher_type, //券类型。可枚举，暂时只支持代金券(FIX_VOUCHER)、无资金单品代金券（ITEM_CASHLESS_FIX_VOUCHER）、无资金单品折扣券（ITEM_CASHLESS_DISCOUNT_VOUCHER）、无资金单品特价券（ITEM_CASHLESS_SPE_VOUCHER）
//                            'voucher_name' => $result->$responseNode->voucher_name, //券名称
//                            'publish_start_time' => $result->$responseNode->publish_start_time, //发放开始时间，格式为：2017-01-01 00:00:01
//                            'publish_end_time' => $result->$responseNode->publish_end_time, //发放结束时间，格式为：2017-01-29 23:59:59
//                            'status' => $result->$responseNode->status, //模板状态，可枚举。分别为‘草稿’(I)、‘生效’(S)、‘删除’(D)和‘过期’(E)
//                            'voucher_valid_period' => $result->$responseNode->voucher_valid_period, //json,券有效期。有两种类型：绝对时间和相对时间。绝对时间有3个key：type、start、end，type取值固定为"ABSOLUTE"，start和end分别表示券生效时间和失效时间，格式为yyyy-MM-dd HH:mm:ss。绝对时间示例：{"type": "ABSOLUTE", "start": "2017-01-10 00:00:00", "end": "2017-01-13 23:59:59"}。相对时间有3个key：type、duration、unit，type取值固定为"RELATIVE"，duration表示从发券时间开始到往后推duration个单位时间为止作为券的使用有效期，unit表示有效时间单位，有效时间单位可枚举：MINUTE, HOUR, DAY。示例：{"type": "RELATIVE", "duration": 1 , "unit": "DAY" }，如果此刻发券，那么该券从现在开始生效1(duration)天(unit)后失效
//                            'floor_amount' => $result->$responseNode->floor_amount, //最低额度。券的最低使用门槛金额，只有订单金额大于等于最低额度时券才能使用。币种为人民币，单位为元。该数值不小于0，小数点以后最多保留两位。
//                            'voucher_description' => $result->$responseNode->voucher_description, //券使用说明
//                            'amount' => $result->$responseNode->amount, //面额。每张代金券可以抵扣的金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位。当券类型为无资金单品券（ITEM_CASHLESS_FIX_VOUCHER、ITEM_CASHLESS_DISCOUNT_VOUCHER、ITEM_CASHLESS_SPE_VOUCHER）时，暂不支持查询本参数，出参为0
//                            'voucher_quantity' => $result->$responseNode->voucher_quantity, //拟发行券的数量。单位为张。该数值是大于0的整数
//                            'total_amount' => $result->$responseNode->total_amount, //总金额面额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位。仅代金券有效。当券类型为无资金单品券（ITEM_CASHLESS_FIX_VOUCHER、ITEM_CASHLESS_DISCOUNT_VOUCHER、ITEM_CASHLESS_SPE_VOUCHER）时，暂不支持查询本参数，出参为0
//                            'publish_count' => $result->$responseNode->publish_count, //已发放张数。单位为张。该数值是大于0的整数
//                            'publish_amount' => $result->$responseNode->publish_amount, //已发放总金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
//                            'used_count' => $result->$responseNode->used_count, //已使用张数。单位为张。该数值是大于0的整数
//                            'used_amount' => $result->$responseNode->used_amount, //已使用总金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
//                            'recycle_amount' => isset($result->$responseNode->recycle_amount) ? $result->$responseNode->recycle_amount : 0 //选填,退回金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
//                        ]
//                    ]);
                } else {
                    return json_encode([
                        'status' => 2,
                        'message' => $result->$responseNode->sub_msg . $result->$responseNode->sub_code,
                        'result_code' => $resultCode,
                    ]);
                }

            }

        } catch (\Exception $exception) {
            return json_encode([
                'status' => 2,
                'message' => $exception->getMessage(),
            ]);
        }


    }


    //核销明细
    public function voucherList(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $storeId = $request->get('storeId', '');
            $where = [];
            if ($storeId) {
                $where[] = ['store_id', '=', $storeId];
            }
            $obj = DB::table('alipay_cash_cards as c')
                ->select('c.*', 't.brand_name as brand_name', 't.amount as amount', 't.floor_amount as floor_amount')
                ->leftjoin('alipay_cash_coupons as t', function ($join) use ($storeId) {
                    $join->on('t.out_biz_no', '=', 'c.out_biz_no');
//                    $join->where('c.store_id', '=', $storeId);
                })
                ->where('c.store_id', '=', $storeId);
            $this->message = '数据返回成功';
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('c.updated_at', 'desc')->get();

            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);
        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }

    public function voucherTemList(Request $request)
    {
        try {
            $public = $this->parseToken();
            $config_id = $public->config_id;
            $storeId = $request->get('storeId', '');
            $templateId = $request->get('templateId', '');

            $where = [];
            if ($storeId) {
                $where[] = ['store_id', '=', $storeId];
            }
            if ($templateId) {
                $where[] = ['template_id', '=', $templateId];
            }

            $obj = DB::table('alipay_cash_cards')->where($where)
                ->orderBy('created_at', 'desc');
            $this->message = '数据返回成功';
            $this->t = $obj->count();
            $data = $this->page($obj)->orderBy('updated_at', 'desc')->get();
            $this->status = 1;
            $this->message = '数据返回成功';
            return $this->format($data);


        } catch (\Exception $exception) {
            return json_encode([
                'status' => -1,
                'message' => $exception->getMessage()
            ]);
        }
    }





}